﻿'use strict';
(function () {
    var app = angular.module('MyDirectives', []);

    app.directive('dateFormat', ['$filter', function ($filter) {
        var dateFilter = $filter('formatDate');
        return {
            require: '?ngModel',
            link: function (scope, elm, attrs, ctrl) {
                function formatter(value) {
                    return dateFilter(value); //format
                }

                function parser() {
                    return ctrl.$modelValue;
                }

                ctrl.$formatters.push(formatter);
                ctrl.$parsers.unshift(parser);
            }
        };
    }]);

    app.directive('cancelTimer', ['$interval', 'utils', function ($interval, utils) {
        function link($scope, element, attributes) {
            // 当DOM元素从页面中被移除时，AngularJS将会在scope中触发$destory事件。这让我们可以有机会来cancel任何潜在的定时器
            $scope.$on("$destroy", function (event) {
                var timer1 = utils.getData('timer1');
                if (timer1) $interval.cancel(timer1);

                var timer2 = utils.getData('timer2');
                if (timer2) $interval.cancel(timer2);

                var timer3 = utils.getData('timer3');
                if (timer3) $interval.cancel(timer3);

                var timer4 = utils.getData('timer4');
                if (timer4) $interval.cancel(timer4);

                var timer5 = utils.getData('timer5');
                if (timer5) $interval.cancel(timer5);
            });
        }

        // 返回指令的配置
        return ({ link: link, scope: false });
    }]);
})();